// 随机装备道具系统 - 程序化生成和动态属性
class EquipmentSystem {
    constructor() {
        this.weaponDatabase = this.initializeWeaponDatabase();
        this.itemDatabase = this.initializeItemDatabase();
        this.rarityWeights = {
            common: 50,
            rare: 25,
            epic: 15,
            legendary: 8,
            mythic: 2
        };
        
        this.weaponPrefixes = [
            { name: '锋利的', effect: { damage: 1.2 }, rarity: 'common' },
            { name: '强化的', effect: { damage: 1.15, fireRate: 0.9 }, rarity: 'rare' },
            { name: '精密的', effect: { accuracy: 1.3 }, rarity: 'rare' },
            { name: '迅猛的', effect: { fireRate: 0.7, damage: 0.95 }, rarity: 'epic' },
            { name: '破坏者', effect: { damage: 1.5, piercing: true }, rarity: 'epic' },
            { name: '屠戮者', effect: { damage: 1.8, lifesteal: 0.15 }, rarity: 'legendary' },
            { name: '末日', effect: { damage: 2.0, explosive: true }, rarity: 'legendary' },
            { name: '神圣的', effect: { damage: 1.3, healing: true }, rarity: 'mythic' },
            { name: '混沌', effect: { damage: 2.5, cursed: true }, rarity: 'mythic' }
        ];
        
        this.weaponSuffixes = [
            { name: '毁灭', effect: { explosive: true }, rarity: 'epic' },
            { name: '穿透', effect: { piercing: true }, rarity: 'rare' },
            { name: '冰霜', effect: { freeze: true }, rarity: 'rare' },
            { name: '烈焰', effect: { burn: true }, rarity: 'epic' },
            { name: '雷电', effect: { shock: true }, rarity: 'epic' },
            { name: '吸血', effect: { lifesteal: 0.1 }, rarity: 'legendary' },
            { name: '时间', effect: { slow: true }, rarity: 'legendary' },
            { name: '虚空', effect: { void: true }, rarity: 'mythic' }
        ];
        
        this.currentEquipment = {};
        this.equipmentEffects = {};
    }
    
    initializeWeaponDatabase() {
        return {
            pistol: {
                name: '手枪',
                type: 'ranged',
                baseStats: {
                    damage: 25,
                    fireRate: 300,
                    accuracy: 0.85,
                    range: 200,
                    ammo: 12,
                    maxAmmo: 60,
                    reloadTime: 1500
                },
                description: '标准配发手枪，平衡可靠'
            },
            rifle: {
                name: '步枪',
                type: 'ranged',
                baseStats: {
                    damage: 45,
                    fireRate: 600,
                    accuracy: 0.9,
                    range: 300,
                    ammo: 30,
                    maxAmmo: 120,
                    reloadTime: 2000
                },
                description: '军用突击步枪，威力强大'
            },
            shotgun: {
                name: '霰弹枪',
                type: 'ranged',
                baseStats: {
                    damage: 80,
                    fireRate: 1200,
                    accuracy: 0.6,
                    range: 150,
                    ammo: 8,
                    maxAmmo: 32,
                    reloadTime: 2500,
                    spread: 5
                },
                description: '近距离杀伤利器'
            },
            smg: {
                name: '冲锋枪',
                type: 'ranged',
                baseStats: {
                    damage: 20,
                    fireRate: 150,
                    accuracy: 0.7,
                    range: 180,
                    ammo: 40,
                    maxAmmo: 200,
                    reloadTime: 1800
                },
                description: '高射速近战武器'
            },
            sniper: {
                name: '狙击枪',
                type: 'ranged',
                baseStats: {
                    damage: 120,
                    fireRate: 2000,
                    accuracy: 0.95,
                    range: 500,
                    ammo: 5,
                    maxAmmo: 25,
                    reloadTime: 3000
                },
                description: '远程精确打击武器'
            },
            minigun: {
                name: '机枪',
                type: 'ranged',
                baseStats: {
                    damage: 35,
                    fireRate: 100,
                    accuracy: 0.6,
                    range: 250,
                    ammo: 100,
                    maxAmmo: 500,
                    reloadTime: 4000,
                    spinUp: 1000
                },
                description: '重型火力压制武器'
            }
        };
    }
    
    initializeItemDatabase() {
        return {
            healthPotion: {
                name: '治疗药水',
                type: 'consumable',
                effect: { healAmount: 50 },
                description: '立即恢复50点生命值',
                rarity: 'common'
            },
            bigHealthPotion: {
                name: '大治疗药水',
                type: 'consumable', 
                effect: { healAmount: 100 },
                description: '立即恢复100点生命值',
                rarity: 'rare'
            },
            ammoBox: {
                name: '弹药箱',
                type: 'consumable',
                effect: { ammoAmount: 60 },
                description: '补充60发弹药',
                rarity: 'common'
            },
            shieldGenerator: {
                name: '护盾发生器',
                type: 'consumable',
                effect: { shield: 75, duration: 30000 },
                description: '30秒内获得75点护盾',
                rarity: 'epic'
            },
            speedBooster: {
                name: '速度增强器',
                type: 'consumable',
                effect: { speedMultiplier: 1.5, duration: 20000 },
                description: '20秒内移动速度增加50%',
                rarity: 'rare'
            },
            damageBooster: {
                name: '伤害增强器',
                type: 'consumable',
                effect: { damageMultiplier: 1.8, duration: 15000 },
                description: '15秒内伤害增加80%',
                rarity: 'epic'
            },
            invincibilityPotion: {
                name: '无敌药水',
                type: 'consumable',
                effect: { invincible: true, duration: 5000 },
                description: '5秒内免疫所有伤害',
                rarity: 'legendary'
            },
            explosiveAmmo: {
                name: '爆炸弹药',
                type: 'consumable',
                effect: { explosiveBullets: true, duration: 30000 },
                description: '30秒内子弹造成爆炸伤害',
                rarity: 'epic'
            },
            piercingAmmo: {
                name: '穿甲弹药',
                type: 'consumable',
                effect: { piercingBullets: true, duration: 30000 },
                description: '30秒内子弹可以穿透敌人',
                rarity: 'rare'
            },
            cursedAmmo: {
                name: '诅咒弹药',
                type: 'consumable',
                effect: { 
                    damageMultiplier: 2.5, 
                    speedMultiplier: 0.7,
                    healthDrain: 2,
                    duration: 20000 
                },
                description: '伤害大幅提升但会持续消耗生命',
                rarity: 'mythic'
            }
        };
    }
    
    // 生成随机武器
    generateRandomWeapon(forceRarity = null) {
        const rarity = forceRarity || this.selectRandomRarity();
        const baseWeaponKey = this.selectRandomBaseWeapon();
        const baseWeapon = this.weaponDatabase[baseWeaponKey];
        
        const weapon = this.createEnhancedWeapon(baseWeapon, rarity);
        weapon.id = this.generateItemId();
        weapon.originalType = baseWeaponKey;
        
        console.log(`🔫 生成随机武器: ${weapon.name} (${rarity})`);
        return weapon;
    }
    
    createEnhancedWeapon(baseWeapon, rarity) {
        const weapon = JSON.parse(JSON.stringify(baseWeapon)); // 深拷贝
        
        // 根据稀有度应用基础数值增强
        const rarityMultipliers = {
            common: { damage: 1.0, fireRate: 1.0, accuracy: 1.0 },
            rare: { damage: 1.2, fireRate: 0.9, accuracy: 1.1 },
            epic: { damage: 1.5, fireRate: 0.8, accuracy: 1.2 },
            legendary: { damage: 2.0, fireRate: 0.7, accuracy: 1.3 },
            mythic: { damage: 3.0, fireRate: 0.6, accuracy: 1.5 }
        };
        
        const multipliers = rarityMultipliers[rarity];
        Object.keys(multipliers).forEach(stat => {
            if (weapon.baseStats[stat]) {
                weapon.baseStats[stat] *= multipliers[stat];
            }
        });
        
        // 应用前缀和后缀
        weapon.modifiers = [];
        weapon.specialEffects = [];
        
        if (rarity !== 'common') {
            this.applyRandomPrefix(weapon, rarity);
        }
        
        if (rarity === 'epic' || rarity === 'legendary' || rarity === 'mythic') {
            this.applyRandomSuffix(weapon, rarity);
        }
        
        if (rarity === 'mythic') {
            // 神话武器额外效果
            this.applyMythicEffects(weapon);
        }
        
        // 生成新名称
        weapon.originalName = weapon.name;
        weapon.name = this.generateWeaponName(weapon, rarity);
        weapon.rarity = rarity;
        
        // 计算最终属性
        this.calculateFinalStats(weapon);
        
        return weapon;
    }
    
    applyRandomPrefix(weapon, rarity) {
        const availablePrefixes = this.weaponPrefixes.filter(prefix => 
            this.isRarityAllowed(prefix.rarity, rarity)
        );
        
        if (availablePrefixes.length > 0) {
            const prefix = availablePrefixes[Math.floor(Math.random() * availablePrefixes.length)];
            weapon.prefix = prefix;
            weapon.modifiers.push(prefix);
            this.applyEffects(weapon, prefix.effect);
        }
    }
    
    applyRandomSuffix(weapon, rarity) {
        const availableSuffixes = this.weaponSuffixes.filter(suffix => 
            this.isRarityAllowed(suffix.rarity, rarity)
        );
        
        if (availableSuffixes.length > 0) {
            const suffix = availableSuffixes[Math.floor(Math.random() * availableSuffixes.length)];
            weapon.suffix = suffix;
            weapon.modifiers.push(suffix);
            this.applyEffects(weapon, suffix.effect);
        }
    }
    
    applyMythicEffects(weapon) {
        // 神话武器的特殊效果
        const mythicEffects = [
            { name: 'soulbound', description: '武器与灵魂绑定，永不丢失' },
            { name: 'evolving', description: '武器会随使用而成长' },
            { name: 'reality_tear', description: '攻击可以撕裂现实' },
            { name: 'time_distortion', description: '改变时间流速' }
        ];
        
        const effect = mythicEffects[Math.floor(Math.random() * mythicEffects.length)];
        weapon.mythicEffect = effect;
        weapon.specialEffects.push(effect);
    }
    
    applyEffects(weapon, effects) {
        Object.entries(effects).forEach(([key, value]) => {
            switch (key) {
                case 'damage':
                    weapon.baseStats.damage *= value;
                    break;
                case 'fireRate':
                    weapon.baseStats.fireRate *= value;
                    break;
                case 'accuracy':
                    weapon.baseStats.accuracy *= value;
                    break;
                default:
                    // 特殊效果
                    weapon.specialEffects.push({ type: key, value: value });
                    break;
            }
        });
    }
    
    generateWeaponName(weapon, rarity) {
        let name = weapon.originalName;
        
        if (weapon.prefix) {
            name = weapon.prefix.name + name;
        }
        
        if (weapon.suffix) {
            name = name + '·' + weapon.suffix.name;
        }
        
        return name;
    }
    
    calculateFinalStats(weapon) {
        // 确保数值为整数
        weapon.baseStats.damage = Math.floor(weapon.baseStats.damage);
        weapon.baseStats.fireRate = Math.floor(weapon.baseStats.fireRate);
        
        // 限制精确度
        weapon.baseStats.accuracy = Math.min(0.98, weapon.baseStats.accuracy);
    }
    
    // 生成随机道具
    generateRandomItem(forceRarity = null) {
        const rarity = forceRarity || this.selectRandomRarity();
        const itemKeys = Object.keys(this.itemDatabase).filter(key => {
            const item = this.itemDatabase[key];
            return this.isRarityAllowed(item.rarity, rarity);
        });
        
        if (itemKeys.length === 0) {
            return this.generateRandomItem('common'); // 回退到通用道具
        }
        
        const itemKey = itemKeys[Math.floor(Math.random() * itemKeys.length)];
        const baseItem = this.itemDatabase[itemKey];
        
        const item = JSON.parse(JSON.stringify(baseItem));
        item.id = this.generateItemId();
        item.originalType = itemKey;
        
        // 根据稀有度增强道具效果
        this.enhanceItemByRarity(item, rarity);
        
        console.log(`💎 生成随机道具: ${item.name} (${rarity})`);
        return item;
    }
    
    enhanceItemByRarity(item, rarity) {
        const rarityMultipliers = {
            common: 1.0,
            rare: 1.3,
            epic: 1.6,
            legendary: 2.0,
            mythic: 2.5
        };
        
        const multiplier = rarityMultipliers[rarity];
        
        // 增强数值效果
        Object.keys(item.effect).forEach(key => {
            if (typeof item.effect[key] === 'number') {
                item.effect[key] = Math.floor(item.effect[key] * multiplier);
            }
        });
        
        item.rarity = rarity;
    }
    
    // 使用道具
    useItem(item) {
        if (!item || item.type !== 'consumable') {
            console.warn('无效的可消耗道具');
            return false;
        }
        
        try {
            this.applyItemEffect(item);
            this.showItemUseEffect(item);
            console.log(`使用道具: ${item.name}`);
            return true;
        } catch (error) {
            console.error('使用道具失败:', error);
            return false;
        }
    }
    
    applyItemEffect(item) {
        const effect = item.effect;
        
        Object.entries(effect).forEach(([key, value]) => {
            switch (key) {
                case 'healAmount':
                    this.healPlayer(value);
                    break;
                case 'ammoAmount':
                    this.restoreAmmo(value);
                    break;
                case 'shield':
                    this.applyShield(value, effect.duration);
                    break;
                case 'speedMultiplier':
                    this.applyTemporaryEffect('speed', value, effect.duration);
                    break;
                case 'damageMultiplier':
                    this.applyTemporaryEffect('damage', value, effect.duration);
                    break;
                case 'invincible':
                    this.applyInvincibility(effect.duration);
                    break;
                case 'explosiveBullets':
                    this.applyTemporaryEffect('explosive', true, effect.duration);
                    break;
                case 'piercingBullets':
                    this.applyTemporaryEffect('piercing', true, effect.duration);
                    break;
                case 'healthDrain':
                    this.applyHealthDrain(value, effect.duration);
                    break;
            }
        });
    }
    
    healPlayer(amount) {
        if (window.player) {
            window.player.health = Math.min(window.player.maxHealth, window.player.health + amount);
            window.player.updateHealthUI();
            
            // 显示治疗效果
            this.showFloatingText(`+${amount}`, window.player.x, window.player.y - 20, '#00ff00');
        }
    }
    
    restoreAmmo(amount) {
        if (window.player && window.player.currentWeapon) {
            const weapon = window.player.currentWeapon;
            weapon.totalAmmo = Math.min(weapon.maxAmmo, weapon.totalAmmo + amount);
            
            // 显示弹药恢复效果
            this.showFloatingText(`弹药 +${amount}`, window.player.x, window.player.y - 30, '#ffff00');
        }
    }
    
    applyShield(amount, duration) {
        if (window.player) {
            window.player.shield = (window.player.shield || 0) + amount;
            window.player.maxShield = window.player.shield;
            
            // 护盾效果
            setTimeout(() => {
                if (window.player) {
                    window.player.shield = 0;
                    window.player.maxShield = 0;
                }
            }, duration);
            
            this.showFloatingText(`护盾 +${amount}`, window.player.x, window.player.y - 40, '#00ffff');
        }
    }
    
    applyTemporaryEffect(type, value, duration) {
        const effectId = 'temp_' + type + '_' + Date.now();
        
        // 应用效果
        switch (type) {
            case 'speed':
                if (window.player) {
                    window.player.speed *= value;
                }
                break;
            case 'damage':
                if (window.roguelikeSystem) {
                    window.roguelikeSystem.activeEffects.damageMultiplier *= value;
                    window.roguelikeSystem.applyPlayerUpgrades();
                }
                break;
            case 'explosive':
                if (window.roguelikeSystem) {
                    window.roguelikeSystem.activeEffects.explosiveBullets = true;
                    window.roguelikeSystem.applyPlayerUpgrades();
                }
                break;
            case 'piercing':
                if (window.roguelikeSystem) {
                    window.roguelikeSystem.activeEffects.piercingBullets = true;
                    window.roguelikeSystem.applyPlayerUpgrades();
                }
                break;
        }
        
        // 记录效果以便移除
        this.equipmentEffects[effectId] = { type, value, startTime: Date.now() };
        
        // 定时移除效果
        setTimeout(() => {
            this.removeTemporaryEffect(effectId);
        }, duration);
        
        this.showFloatingText(`${type.toUpperCase()} 增强!`, window.player.x, window.player.y - 50, '#ff00ff');
    }
    
    removeTemporaryEffect(effectId) {
        const effect = this.equipmentEffects[effectId];
        if (!effect) return;
        
        // 移除效果
        switch (effect.type) {
            case 'speed':
                if (window.player) {
                    window.player.speed /= effect.value;
                }
                break;
            case 'damage':
                if (window.roguelikeSystem) {
                    window.roguelikeSystem.activeEffects.damageMultiplier /= effect.value;
                    window.roguelikeSystem.applyPlayerUpgrades();
                }
                break;
            case 'explosive':
                if (window.roguelikeSystem) {
                    window.roguelikeSystem.activeEffects.explosiveBullets = false;
                    window.roguelikeSystem.applyPlayerUpgrades();
                }
                break;
            case 'piercing':
                if (window.roguelikeSystem) {
                    window.roguelikeSystem.activeEffects.piercingBullets = false;
                    window.roguelikeSystem.applyPlayerUpgrades();
                }
                break;
        }
        
        delete this.equipmentEffects[effectId];
    }
    
    applyInvincibility(duration) {
        if (window.player) {
            const originalTakeDamage = window.player.takeDamage;
            window.player.takeDamage = () => {}; // 免疫伤害
            window.player.invincible = true;
            
            // 添加视觉效果
            this.showInvincibilityEffect();
            
            setTimeout(() => {
                if (window.player) {
                    window.player.takeDamage = originalTakeDamage;
                    window.player.invincible = false;
                }
            }, duration);
            
            this.showFloatingText('无敌状态!', window.player.x, window.player.y - 60, '#ffd700');
        }
    }
    
    applyHealthDrain(drainRate, duration) {
        const drainInterval = setInterval(() => {
            if (window.player && window.player.health > 1) {
                window.player.health -= drainRate;
                window.player.updateHealthUI();
                this.showFloatingText(`-${drainRate}`, window.player.x, window.player.y, '#ff0000');
            }
        }, 1000);
        
        setTimeout(() => {
            clearInterval(drainInterval);
        }, duration);
    }
    
    showItemUseEffect(item) {
        // 创建道具使用特效
        const effect = document.createElement('div');
        effect.className = 'item-use-effect';
        effect.innerHTML = `
            <div class="item-effect-content">
                <div class="item-name">${item.name}</div>
                <div class="item-description">${item.description}</div>
            </div>
        `;
        
        document.body.appendChild(effect);
        
        // 添加样式
        this.addItemEffectStyles();
        
        // 2秒后移除
        setTimeout(() => {
            if (effect.parentNode) {
                effect.style.animation = 'fadeOut 0.5s ease-out';
                setTimeout(() => {
                    if (effect.parentNode) {
                        document.body.removeChild(effect);
                    }
                }, 500);
            }
        }, 2000);
    }
    
    showFloatingText(text, x, y, color = '#ffffff') {
        if (window.gameEngine && window.gameEngine.floatingTexts) {
            window.gameEngine.floatingTexts.push({
                text: text,
                x: x,
                y: y,
                color: color,
                life: 2000,
                maxLife: 2000,
                vy: -1
            });
        }
    }
    
    showInvincibilityEffect() {
        if (!window.player) return;
        
        // 创建无敌光环效果
        const canvas = document.getElementById('gameCanvas');
        if (!canvas) return;
        
        const glowOverlay = document.createElement('div');
        glowOverlay.id = 'invincibilityGlow';
        glowOverlay.style.cssText = `
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: radial-gradient(circle at ${window.player.x}px ${window.player.y}px, 
                rgba(255, 215, 0, 0.3) 50px, 
                transparent 100px);
            pointer-events: none;
            z-index: 1000;
            animation: invincibilityPulse 0.5s ease-in-out infinite alternate;
        `;
        
        canvas.parentNode.appendChild(glowOverlay);
        
        // 5秒后移除
        setTimeout(() => {
            if (glowOverlay.parentNode) {
                glowOverlay.parentNode.removeChild(glowOverlay);
            }
        }, 5000);
    }
    
    // 工具方法
    selectRandomRarity() {
        const totalWeight = Object.values(this.rarityWeights).reduce((sum, weight) => sum + weight, 0);
        let random = Math.random() * totalWeight;
        
        for (const [rarity, weight] of Object.entries(this.rarityWeights)) {
            random -= weight;
            if (random <= 0) {
                return rarity;
            }
        }
        
        return 'common';
    }
    
    selectRandomBaseWeapon() {
        const weaponKeys = Object.keys(this.weaponDatabase);
        return weaponKeys[Math.floor(Math.random() * weaponKeys.length)];
    }
    
    isRarityAllowed(requiredRarity, currentRarity) {
        const rarityOrder = ['common', 'rare', 'epic', 'legendary', 'mythic'];
        const requiredIndex = rarityOrder.indexOf(requiredRarity);
        const currentIndex = rarityOrder.indexOf(currentRarity);
        return currentIndex >= requiredIndex;
    }
    
    generateItemId() {
        return 'item_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
    }
    
    // 获取稀有度颜色
    getRarityColor(rarity) {
        const colors = {
            common: '#ffffff',
            rare: '#3498db',
            epic: '#9b59b6',
            legendary: '#f39c12',
            mythic: '#e74c3c'
        };
        return colors[rarity] || colors.common;
    }
    
    // 在游戏世界中生成装备掉落
    spawnEquipmentDrop(x, y, forceType = null, forceRarity = null) {
        const dropType = forceType || (Math.random() < 0.7 ? 'weapon' : 'item');
        
        let drop;
        if (dropType === 'weapon') {
            drop = this.generateRandomWeapon(forceRarity);
            drop.type = 'weapon_pickup';
        } else {
            drop = this.generateRandomItem(forceRarity);
            drop.type = 'item_pickup';
        }
        
        drop.x = x;
        drop.y = y;
        drop.width = 25;
        drop.height = 25;
        drop.pickupRadius = 40;
        
        // 添加到游戏世界
        if (window.gameEngine) {
            if (dropType === 'weapon') {
                window.gameEngine.weapons.push(drop);
            } else {
                window.gameEngine.powerUps.push(drop);
            }
        }
        
        console.log(`📦 生成装备掉落: ${drop.name} at (${x}, ${y})`);
        return drop;
    }
    
    addItemEffectStyles() {
        if (document.getElementById('itemEffectStyles')) return;
        
        const styles = document.createElement('style');
        styles.id = 'itemEffectStyles';
        styles.textContent = `
            .item-use-effect {
                position: fixed;
                top: 20%;
                left: 50%;
                transform: translateX(-50%);
                z-index: 12000;
                animation: itemEffectEntry 1s ease-out;
            }
            
            .item-effect-content {
                background: linear-gradient(135deg, rgba(0, 255, 136, 0.9), rgba(0, 255, 136, 0.7));
                border: 2px solid #00ff88;
                border-radius: 15px;
                padding: 15px 20px;
                text-align: center;
                color: white;
                box-shadow: 0 0 25px rgba(0, 255, 136, 0.5);
            }
            
            .item-name {
                font-size: 18px;
                font-weight: bold;
                margin-bottom: 5px;
            }
            
            .item-description {
                font-size: 14px;
                opacity: 0.9;
            }
            
            @keyframes itemEffectEntry {
                0% {
                    opacity: 0;
                    transform: translateX(-50%) translateY(-30px);
                }
                100% {
                    opacity: 1;
                    transform: translateX(-50%) translateY(0);
                }
            }
            
            @keyframes invincibilityPulse {
                0% { opacity: 0.3; }
                100% { opacity: 0.7; }
            }
        `;
        
        document.head.appendChild(styles);
    }
}

// 全局实例
window.equipmentSystem = new EquipmentSystem();

console.log('装备道具系统已加载');